home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 12285 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: news.primenet.com!jstern
  2. From: jstern@primenet.com (Josh Stern)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: what getline returns? Nobody can explain this!!
  5. Date: 18 Mar 1996 18:11:01 -0700
  6. Organization: Primenet Services for the Internet
  7. Sender: root@primenet.com
  8. Distribution: na
  9. Message-ID: <4il1j5$525@nnrp1.news.primenet.com>
  10. References: <4ifbk8$6nf@bcarh8ab.bnr.ca>
  11. X-Posted-By: jstern@usr3.primenet.com
  12.  
  13. In article <4ifbk8$6nf@bcarh8ab.bnr.ca>, whyme <liyu@bnr.ca> wrote:
  14. >getline member fuction in ifstream is supposed to return the
  15. >receiving object (that is, ostream&). 
  16. >
  17. >However, many books contain the code samples like:
  18. >
  19. >ifstream in("tmp.txt");
  20. >while (in.getline(buffer,sizeof(buffer))) { ...  }
  21. >
  22. >This loop quits only if in.getline returns 0 or NUll;
  23. >                ^^^^^^^
  24. >
  25. >but an ostream object is neither 0 nor NULL;
  26. >the result is an object, not integer or pointer.
  27. >
  28. >So how can this loop quit?
  29. >
  30. >It works; but no one I know can explain this!!!!
  31. >Thanks for your help.
  32.  
  33. It works because ostream or one of the base classes that
  34. it inherits from has defined a type conversion to a
  35. type that can be logically tested in this manner, and
  36. thus supports the type of useful and familiar idiom
  37. that you described.  Here is a relevant portion of
  38. the g++ implementation of class ios, that is a
  39. base class for the iostreams:
  40.  
  41.     int fail() const { return _state & (ios::badbit|ios::failbit); }
  42.     int bad() const { return _state & ios::badbit; }
  43.     iostate rdstate() const { return _state; }
  44.     operator void*() const { return fail() ? (void*)0 : (void*)(-1); }
  45.     int operator!() const { return fail(); }
  46.  
  47. So any code that would work with a FILE* variable by
  48. testing whether the pointer is NULL, would work with ios and
  49. descendants, since the compiler would invoke the type conversion
  50. to void* (assuming no further overloading).
  51.  
  52. - Josh
  53.  
  54.  
  55. --
  56. -------------------------------------------------------------------------------
  57. jstern
  58. jstern@primenet.com
  59. -------------------------------------------------------------------------------
  60.